import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:news/com.comm/widget/text_field_item.dart';

import '../contants/writer_type.dart';
import '../model/db_utils.dart';
import '../utils/StringUtils.dart';
import '../utils/utils.dart';
import '../utils/widget_utils.dart';

/**
 * 列表显示
 */
class TranslateShowList extends StatefulWidget {
  final String resPath;

  TranslateShowList({Key? key, required this.resPath}) : super(key: key);

  @override
  _TranslateShowListState createState() => _TranslateShowListState();
}

class _TranslateShowListState extends State<TranslateShowList> {
  final TextEditingController _controller_key =
      TextEditingController(); //要查询的多语言
  final TextEditingController _controller_path = TextEditingController(); //路径
  Map<dynamic, dynamic> transMap = {}; // 要预览的多语言数据
  final db = DbUtils();

  @override
  void initState() {
    super.initState();
    setState(() {
      _controller_path.text = widget.resPath.trim();
    });
  }

  /**
   * 显示选择多语言路径弹窗
   */
  void _showSelectResPathDialog(BuildContext context) async {
    String? arrString = await db.loadResListPath();
    if (arrString != null && arrString.isNotEmpty) {
      debugPrint("arrString:${arrString}");
      var map = await jsonDecode(arrString);
      List<String> list = map.keys.toList();
      showResListSelectDialog(context, "选择多语言写入路径", list, (path) {
        debugPrint("选择的路径:${path}");
        setState(() {
          _controller_path.text = map[path];
        });
      });
    } else {
      showToast("请先添加多语言写入路径");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        SizedBox(
          height: 16,
        ),
        SizedBox(
            width: 1000,
            child: Row(children: [
              SizedBox(
                  width: 200,
                  child: Padding(
                      padding:
                          EdgeInsets.symmetric(horizontal: 0.0, vertical: 0.0),
                      child: getTextWidget(16, "当前多语言路径 :", Colors.black))),
              SizedBox(
                width: 16,
              ),
              SizedBox(
                  width: 680,
                  child: TextField(
                    controller: _controller_path,
                    decoration: InputDecoration(
                      labelText: '请选择当前多语言路径',
                      hintText: '请选择当前多语言路径',
                      border: OutlineInputBorder(),
                    ),
                  )),
              Padding(
                  padding: EdgeInsets.only(left: 8),
                  child: SizedBox(
                    child: IconButton(
                      icon: Icon(Icons.more_horiz_rounded),
                      onPressed: () async {
                        _showSelectResPathDialog(context);
                      },
                    ),
                    width: 70,
                  )),
            ])),
        SizedBox(
          height: 16,
        ),
        SizedBox(
            width: 1000,
            child: Row(children: [
              SizedBox(
                  width: 200,
                  child: Padding(
                      padding:
                          EdgeInsets.symmetric(horizontal: 0.0, vertical: 0.0),
                      child: getTextWidget(16, "要预览的key :", Colors.black))),
              SizedBox(
                width: 16,
              ),
              SizedBox(
                  width: 680,
                  child: TextField(
                    controller: _controller_key,
                    decoration: InputDecoration(
                      labelText: '请输入要预览的多语言key',
                      hintText: '请输入要预览的多语言key',
                      border: OutlineInputBorder(),
                    ),
                  )),
              Padding(
                  padding: EdgeInsets.only(left: 8),
                  child: SizedBox(
                      height: 40,
                      child: ElevatedButton(
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.blue,
                          ),
                          onPressed: () async {
                            String translateKey = _controller_key.text.trim();
                            String resPath = _controller_path.text.trim();
                            Map<dynamic, dynamic> data =
                                await StringsUtils.getTranslateKeyLanguages(
                                    translateKey, resPath);
                            print("查询到的多语言：${data}");
                            if (data.isEmpty) {
                              showToast("该多语言不存在");
                              return;
                            }
                            showLoadingDialog(context, () {},
                                loadingText: "正在查询中...");
                            setState(() {
                              transMap = {};
                            });
                            // 使用.then()来处理延迟完成后的逻辑
                            await Future.delayed(Duration(seconds: 1));
                            setState(() {
                              transMap = data;
                            });
                            Navigator.of(context).pop();
                          },
                          child: getTextWidget(16, "预览", Colors.white)))),
            ])),
        SizedBox(
            width: 1000,
            height: 390,
            child: ListView(
                children: transMap.entries
                    .map((item) => SizedBox(
                        height: 60,
                        child: Row(children: [
                          SizedBox(
                              width: 100, child: Text('当前多语言 ${item.key}')),
                          SizedBox(
                            width: 10,
                          ),
                          Expanded(
                            child: TextFieldItem(
                                onChanged: (key, value) {
                                  transMap[key] = value;
                                  print("数据变化了${transMap[key]}");
                                  setState(() {});
                                },
                                initialKey: item.key,
                                initialValue: item.value,
                                hint: "请确认要修改的多语言"), // 使用索引来显示不同的文本
                          ),
                          SizedBox(
                            width: 10,
                          )
                        ])))
                    .toList())),
        Row(children: <Widget>[
          Expanded(
              child: SizedBox(
            height: 1,
          )),
          TextButton(
            child: Text("更新"),
            onPressed: () async {
              String keyTag = _controller_key.text.trim();
              String resPath = _controller_path.text.trim();

              if (keyTag.isEmpty) {
                showToast("多语言key不能为空");
                return;
              }
              if (transMap.isEmpty ||
                  transMap.keys.isEmpty ||
                  transMap.values.isEmpty) {
                showToast("多语言翻译不能为空");
                return;
              }
              //先移除
              await StringsUtils.removeTranslateByKey(resPath, keyTag);
              print("数据打印：" + transMap.toString());
              //再插入
              await StringsUtils.startInsertLanguage(
                  keyTag, transMap, resPath, WriterType.insert);
              Navigator.pop(context);
              showToast("更新成功");
            },
          ),
          SizedBox(
            width: 16,
          ),
          TextButton(
            child: Text("取消"),
            onPressed: () {
              Navigator.pop(context);
            },
          ),
        ]),
      ],
    );
  }
}
